import webbrowser

import pyperclip
from PyQt5.QtWidgets import QGroupBox, QVBoxLayout, QPushButton, QWidget, QLabel, QHBoxLayout, QComboBox, \
    QTextEdit, QMessageBox

from LanguageTool import getCNfromDict, getCurLang, setCurLang
from LisenceTool import getLisenceInfo_CID, getActStatus, getActCode, runAct
from mylog import addLog


class TabBar04(QWidget):
    def __init__(self):
        super().__init__()

        # 创建垂直布局
        layout = QVBoxLayout()

        # 添加第一个 QGroupBox
        group_box_1 = self.GroupBox_language()
        layout.addWidget(group_box_1)

        # 添加第二个 QGroupBox
        group_box_2 = self.GroupBox_lisence()
        layout.addWidget(group_box_2)

        # 添加第三个 QGroupBox
        group_box_3 = self.GroupBox_help()
        layout.addWidget(group_box_3)

        # 添加第四个 QGroupBox
        group_box_4 = self.GroupBox_duty()
        layout.addWidget(group_box_4)

        # 添加第五个 QGroupBox
        group_box_5 = self.GroupBox_version()
        layout.addWidget(group_box_5)

        # 将主布局设置到窗口中
        self.setLayout(layout)

    def GroupBox_language(self):
        """
        语言设置
        :return:
        """
        def on_combobox_index_changed(index):
            addLog('TabBar04', 'info', f'setCurLang value:{index}')
            setCurLang(index)

        group_box = QGroupBox(getCNfromDict('TabBar04-langset'))  # 创建 QGroupBox
        group_box.setMaximumHeight(100)
        # 创建一个水平布局，用于放置标签和下拉列表
        h_layout = QHBoxLayout()
        # 添加一个标签
        label = QLabel(getCNfromDict('TabBar04-lang'))
        label.setMaximumWidth(200)
        # 添加一个下拉列表
        combo_box = QComboBox()
        combo_box.setMaximumWidth(500)
        combo_box.addItems(["中文", "English"])  # 添加选项
        combo_box.setCurrentIndex(getCurLang())
        combo_box.currentIndexChanged.connect(on_combobox_index_changed)  # 绑定索引变化事件
        # 添加一个标签
        label1 = QLabel(getCNfromDict('TabBar04-lang1'))
        # 将标签和下拉列表添加到水平布局中
        h_layout.addWidget(label)
        h_layout.addWidget(combo_box)
        h_layout.addWidget(label1)
        # 将水平布局设置为 QGroupBox 的布局
        group_box.setLayout(h_layout)
        return group_box

    def GroupBox_lisence(self):
        """
        证书管理
        :return:
        """
        group_box = QGroupBox(getCNfromDict('TabBar04-lisenceset'))  # 创建 QGroupBox
        group_box.setMaximumHeight(300)
        group_box.setMinimumHeight(150)
        # 创建垂直布局
        layout = QVBoxLayout()

        # 创建水平布局
        h_layout1 = QHBoxLayout()
        # 创建 QLabel, QTextEdit 和 QPushButton
        label1 = QLabel(getCNfromDict('TabBar04-cid'))
        text_edit1 = QTextEdit()
        text_edit1.setReadOnly(True)
        text_edit1.setMaximumHeight(30)
        text_edit1.setMinimumHeight(30)
        text_edit1.setText(getLisenceInfo_CID())

        def clickedButton1():
            addLog('TabBar04', 'info', f'copy_cid_btn_clicked')
            pyperclip.copy(text_edit1.toPlainText())
            self.show_message(getCNfromDict('TabBar04-cidcopyed'))

        button1 = QPushButton(getCNfromDict('TabBar04-copycid'))
        button1.clicked.connect(clickedButton1)

        # 将控件添加到水平布局中
        h_layout1.addWidget(label1)
        h_layout1.addWidget(text_edit1)
        h_layout1.addWidget(button1)

        # 创建水平布局
        h_layout2 = QHBoxLayout()
        # 创建 QLabel, QTextEdit 和 QPushButton
        label2 = QLabel(getCNfromDict('TabBar04-actstatus'))
        text_edit2 = QTextEdit()
        text_edit2.setReadOnly(True)
        text_edit2.setMaximumHeight(30)
        text_edit2.setMinimumHeight(30)
        if getActStatus():
            text_edit2.setText(getCNfromDict('TabBar04-acted'))
        else:
            text_edit2.setText(getCNfromDict('TabBar04-unacted'))

        def clickedButton2():
            addLog('TabBar04', 'info', f'buy_code_btn_clicked')
            url = "http://featherstarzone.taobao.com/"
            webbrowser.open(url)

        button2 = QPushButton(getCNfromDict('TabBar04-buycode'))
        button2.clicked.connect(clickedButton2)

        # 将控件添加到水平布局中
        h_layout2.addWidget(label2)
        h_layout2.addWidget(text_edit2)
        h_layout2.addWidget(button2)

        # 创建水平布局
        h_layout3 = QHBoxLayout()
        # 创建 QLabel, QTextEdit 和 QPushButton
        label3 = QLabel(getCNfromDict('TabBar04-actcode'))
        text_edit3 = QTextEdit()
        if getActStatus():
            text_edit3.setReadOnly(True)
        else:
            text_edit3.setReadOnly(False)
        text_edit3.setMinimumHeight(30)
        text_edit3.setMaximumHeight(30)
        text_edit3.setText(getActCode())

        def clickedButton3():
            addLog('TabBar04', 'info', f'act_btn_clicked')
            cervalue = text_edit3.toPlainText().replace(' ', '').replace('\n', '').replace('\r', '')
            res = runAct(text_edit1.toPlainText(), cervalue)
            if res == 0:
                text_edit2.setText(getCNfromDict('TabBar04-acted'))
                button3.setEnabled(False)
                self.show_message(getCNfromDict('TabBar04-actres0'))
                addLog('TabBar04', 'info', f'act finish!')
            elif res == -1:
                self.show_message(getCNfromDict('TabBar04-actres1'))
                addLog('TabBar04', 'warn', f'act code : -1')
            elif res == -2:
                self.show_message(getCNfromDict('TabBar04-actres2'))
                addLog('TabBar04', 'warn', f'act code : -2')
            elif res == -3:
                self.show_message(getCNfromDict('TabBar04-actres3'))
                addLog('TabBar04', 'warn', f'act code : -3')

        button3 = QPushButton(getCNfromDict('TabBar04-act'))
        button3.clicked.connect(clickedButton3)
        if getActStatus():
            button3.setEnabled(False)

        # 将控件添加到水平布局中
        h_layout3.addWidget(label3)
        h_layout3.addWidget(text_edit3)
        h_layout3.addWidget(button3)

        layout.addLayout(h_layout1)
        layout.addLayout(h_layout2)
        layout.addLayout(h_layout3)

        group_box.setLayout(layout)
        return group_box

    def GroupBox_help(self):
        """
        帮助
        :return:
        """
        group_box = QGroupBox(getCNfromDict('TabBar04-help'))  # 创建 QGroupBox
        group_box.setMaximumHeight(300)
        group_box.setMinimumHeight(100)
        # 创建垂直布局
        layout = QVBoxLayout()
        label = QTextEdit()
        label.setReadOnly(True)
        if getCurLang() == 1:
            label.setText("&nbsp;&nbsp;This software was independently developed by the author and provides convenient sound modification tools for car enthusiasts.<br>"
                          "&nbsp;&nbsp;If you encounter difficulties in using it, please read the<b>\"UNI-Z Voice Modification Tool - User Tutorial\"</b>and<b>\"UNI-Z Voice Modification Tool - User Manual\" under this software directory</b>, or through <b>Baidu Netdisk group or WeChat communication group</b>.<br>"
                          "&nbsp;&nbsp;The latest version of the software and its materials will be updated in Baidu Cloud Drive. Please add the Baidu Cloud Drive group number:<b>959535402</b>.<br>"
                          "&nbsp;&nbsp;WeChat communication group: Invite to join the group through Baidu Netdisk group or adding author WeChat account, etc.")
        else:
            label.setText("&nbsp;&nbsp;这款软件由作者独立开发完成，为车友提供方便的音效修改工具。<br>"
                          "&nbsp;&nbsp;在使用上遇到困难，请阅读本软件目录下的<b>《UNI-Z音效修改工具--使用教程》</b>和<b>《UNI-Z音效修改工具--使用手册》</b>，或通过<b>百度网盘群或微信交流群</b>。<br>"
                          "&nbsp;&nbsp;最新版本软件及其资料，都会在百度网盘中更新，请加百度网盘群号：<b>959535402</b>。<br>"
                          "&nbsp;&nbsp;微信交流群：通过百度网盘群或添加作者微信号等方式邀请入群。")
        layout.addWidget(label)
        group_box.setLayout(layout)
        return group_box

    def GroupBox_duty(self):
        """
        责任声明
        :return:
        """
        group_box = QGroupBox(getCNfromDict('TabBar04-dutyavowal'))  # 创建 QGroupBox
        # group_box.setMaximumHeight(300)
        group_box.setMinimumHeight(150)
        # 创建垂直布局
        layout = QVBoxLayout()
        label = QTextEdit()
        label.setReadOnly(True)
        if getCurLang() == 1:
            label.setText("&nbsp;Thank you for your support of this tool software. Before using this software, please carefully read the following statement:<br>"
                          "(1) This software aims to provide users with the ability to modify vehicle sound effects. Users should fully understand the risks that may arise from modifying the vehicle system during use, including but not limited to functional abnormalities, system instability, or other technical issues. Any risks arising from the use of this software shall be borne by the user.<br>"
                          "(2) Before making any modifications to the vehicle using this software, the user is responsible for ensuring that such modifications comply with local laws and regulations, as well as the vehicle manufacturer's terms of use and warranty policies. Any consequences resulting from non-compliance with laws and regulations or violation of warranty terms shall be the sole responsibility of the user.<br>"
                          "(3) To the maximum extent permitted by applicable laws, the developer shall not be liable for any direct or indirect losses caused by the use of this software, including but not limited to data loss, vehicle damage, or other economic losses.<br>"
                          "(4) Users shall be fully responsible for their use of this software and ensure the legality and security of their actions. This tool is for personal use only and is prohibited from being used for any illegal or unauthorized commercial purposes.<br>"
                          "<br>&nbsp;By using this software, you agree to all the terms of this disclaimer. If you do not agree, please stop using this software immediately.")
        else:
            label.setText("&nbsp;&nbsp;感谢您对本工具软件的支持。在使用本软件之前，请仔细阅读以下声明：<br>"
                          "（1）本软件旨在为用户提供修改车辆音效的功能。用户在使用过程中，应充分了解对车辆系统进行修改可能带来的风险，包括但不限于功能异常、系统不稳定或其他技术问题。使用本软件所带来的任何风险由用户自行承担。<br>"
                          "（2）在使用本软件对车辆进行任何修改之前，用户有责任确保此类修改符合当地法律法规以及车辆制造商的使用条款和保修政策。由于不符合法律法规或违反保修条款而导致的任何后果，由用户自行负责。<br>"
                          "（3）在适用法律允许的最大范围内，开发者不对使用本软件造成的任何直接或间接损失负责，包括但不限于数据丢失、车辆损坏、或其他经济损失。<br>"
                          "（4）用户应对其使用本软件的行为负全责，并确保其行为的合法性和安全性。本工具仅供个人使用，禁止用于任何非法或未经授权的商业用途。<br>"
                          "<br>&nbsp;&nbsp;通过使用本软件，即表示您已同意本免责声明的所有条款。如不同意，请立即停止使用本软件。")
        layout.addWidget(label)
        group_box.setLayout(layout)
        return group_box

    def GroupBox_version(self):
        """
        版本信息
        :return:
        """
        group_box = QGroupBox(getCNfromDict('TabBar04-versioninfo'))  # 创建 QGroupBox
        group_box.setMinimumHeight(170)
        # group_box.setMaximumHeight(250)
        # 创建垂直布局
        layout = QVBoxLayout()
        label = QTextEdit()
        label.setReadOnly(True)
        if getCurLang() == 1:
            label.setText("Version: 3.0.2<br>"
                        "Release Date: 2025.03.24<br>"
                        "Version update content:<br>"
                        " - Resolve the issue where low-speed driving sound effects cannot be modified in certain situations<br>"
                        "V3.0.1 (2025.02.25):<br>"
                        " - New UI<br>"
                        " - New software architecture<br>"
                        " - New audio processing function<br>"
                        " - New sound effect data packet processing function<br>"
                        " - Resolve the BUG of not being able to export packages<br>"
                        "<br>**************************************************************<br>"
                        "All rights reserved by <b>FeatherStar Zone(星羽空间工作室)</b>.<br>"
                        "Contact information: <b>(WeChat) FeatherStarStudio_1</b><br>"
                        "<br>"
                        "&nbsp;If you have any comments or suggestions about the tool's features, please feel free to contact and assist the author in continuing to optimize and improve this software!<br>"
                        "&nbsp;If you are interested in collaborating on the development of other software products or smart hardware products, please feel free to contact us at any time!")
        else:
            label.setText("版本号: 3.0.2<br>"
                        "发布日期: 2025年03月24日<br>"
                        "版本更新内容：<br>"
                        " - 解决低速行车音效在某些情况下无法被修改的问题<br>"
                        "V3.0.1 (2025年02月25日):<br>"
                        " - 全新UI<br>"
                        " - 全新软件架构<br>"
                        " - 全新音频处理功能<br>"
                        " - 全新音效数据包处理功能<br>"
                        " - 解决无法导包的BUG<br>"
                        "<br>**************************************************************<br>"
                        "版权所有 <b>星羽空间工作室(FeatherStar Zone)</b>。<br>"
                        "联系方式: <b>（微信号）FeatherStarStudio_1</b><br>"
                        "<br>"
                        "&nbsp;&nbsp;若您对工具功能有意见或建议，欢迎联系、帮助作者继续优化和完善本软件！<br>"
                        "&nbsp;&nbsp;如若您有其他软件产品、智能硬件产品合作开发意愿，请随时联系！")
        layout.addWidget(label)
        group_box.setLayout(layout)
        return group_box

    def create_group_box(self, title, content):
        """
        创建一个 QGroupBox 并填充内容（用于测试的）
        :param title: QGroupBox 的标题
        :param content: QGroupBox 内的内容
        :return: QGroupBox 对象
        """
        group_box = QGroupBox(title)  # 创建 QGroupBox
        group_layout = QVBoxLayout()  # 创建一个 QVBoxLayout 用于组内布局
        label = QLabel(content)  # 创建一个 QLabel 显示内容
        button = QPushButton("按钮")  # 添加一个按钮作为示例
        group_layout.addWidget(label)
        group_layout.addWidget(button)

        # 设置布局到组框
        group_box.setLayout(group_layout)
        return group_box

    def show_message(self, message, type=0):
        """显示提示消息框"""
        msg_box = QMessageBox()
        msg_box.setIcon(QMessageBox.Information)
        if type == 0:
            msg_box.setWindowTitle(getCNfromDict('megboxTitle-tip'))
        else:
            msg_box.setWindowTitle(getCNfromDict('megboxTitle-err'))
        msg_box.setText(message)
        msg_box.setStandardButtons(QMessageBox.Ok)
        msg_box.exec_()

